from collections import defaultdict, deque


def count_food_chain(n, edges):
    # 单向无环图
    graph = defaultdict(list)
    indegrees = [0] * n
    for u, v in edges:
        graph[u].append(v)
        indegrees[v] += 1
    cnt = [0] * n       # 以i节点结尾的路径有多少条
    q = deque()
    for i, indegrees in enumerate(indegrees):
        if indegrees == 0:
            q.append(i)
            cnt[i] = 1      # 入图点，只有一条路到他

    ans = 0
    while q:
        u = q.popleft()
        if graph[u]:
            for v in graph[u]:
                cnt[v] += cnt[u]    # 有多少条路走向u，u由走向v
                indegrees[v] -= 1
                if indegrees[v] == 0:
                    q.append(v)
        else:
            ans += cnt[u]   # u一个结束点, 统计有多少路能走向u
    return ans



